//
//  ConsultationDetailViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/1/31.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
import Networking
import Alamofire
import PKHUD
import SwiftyJSON

class ConsultationDetailViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, ConsultationHeaderViewDelegate, BottomShadow, XHInputViewDelagete, ConsultaionCommentTableViewCellDelegate, AddCornerUIRectCorner {
    
    private var consultationheaderView = ConsultationHeaderView.instanceConsultationHeaderView()
    private var videoHeaderView = HomeVideoHeaderView().instanceHomeVideoHeaderView()
    private var useView = UseView.instanceUseHeaderView()
    var model: ArticleModel?
    var videoModel: VideoModel?
    var data:[SearchRecommendModel] = []
    var recommDatas: [GoodsModel] = []
    var notiName:String?
    
    var commentData:[myCommendModel] = []
    private var consultationDetailType: HomeVCSelect
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    var page:Int = 0
    var totalPage:Int = 0

    var recommBtn: UIButton?
    var jbList:[String]?
    @IBOutlet weak var mainTableView: UITableView!
    @IBOutlet weak var bottomView: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.fetchJbList()
        self.title = model?.title
        self.showRightButtons()
        setUI()
        if self.model?.browse != nil {
            let browseCount:String = "\(Int((self.model?.browse)!)! + 1)"
            fetchArticleDetail(id: (model?.id)!)
            self.model?.browse = browseCount
        }else {
            fetchArticleDetail(id: (model?.id)!)
        }
    }
    
    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, type: HomeVCSelect) {
        consultationDetailType = type
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        consultationDetailType = type
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
    }
    deinit {
        consultationheaderView.scrollViewKVOremove()
    }
//    override func returnVC() {
//        self.navigationController?.popViewController(animated: true)
//    }
    func setUI() {
        mainTableView.register(UINib(nibName: "ConsultaionCommentTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        setNavigation()
        mainTableView.estimatedRowHeight = 100
        mainTableView.rowHeight = UITableViewAutomaticDimension
        
        self.bottomView.addSubview(setButtomView())
        
        let footerAction:Selector = #selector(footerRefresh)
        footer.setRefreshingTarget(self, refreshingAction: footerAction)
        
    }
    override func shoppingCartTap(_ btn: UIButton) {
        
        guard MineInfoModel.share.hasLoginIn() else {
            let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
            self.navigationController?.pushViewController(loginVC, animated: true)
            return
        }
        
        if btn.isSelected{
            cancelCollectionArticle(parameter:  ["objId":(model?.id)!,"objType":"1"], btn: btn)
        }
        else{
            collectionArticle(parameter: ["objId":(model?.id)!,"objType":"1"],btn:btn)
        }
    }
    func showRightButtons() {
        let imageNames = ["right_copy_page"]
        var beforButton: UIButton?
        for (index, imageName) in imageNames.enumerated() {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: imageName), for: .normal)
            button.sizeToFit()
            button.tag = index
            self.view.addSubview(button)
//            self.view.addSubview(button)
            button.snp.makeConstraints({ (make) in
                make.right.equalTo(self.view.snp.right).offset(-12)
                if beforButton == nil {
                    make.centerY.equalTo(self.view.snp.centerY)
                } else {
                    make.top.equalTo(beforButton!.snp.bottom).offset(30)
                }
                
            })
            button.addTarget(self, action: #selector(rightButtonTap1(_ :)), for: .touchUpInside)
            beforButton = button
            recommBtn = button
        }
        
        
    }
    
    @objc func rightButtonTap1(_ btn: UIButton) {
        
        switch btn.tag {
        case 0:
            let imageSize = UIImage(named: "right_copy_page")
            guard let trueImageSize = imageSize else {return}
            if recommDatas.count > 0{
                RelevantRecommendationsView().showData1(datas: recommDatas, rightMargin: trueImageSize.size.width){(index) in
                    let shoppingDetailVC = ShoppingDetailViewController(nibName: "\(ShoppingDetailViewController.self)", bundle: nil)
                    shoppingDetailVC.commodityModel = self.recommDatas[index!]
                    self.navigationController?.pushViewController(shoppingDetailVC, animated: true)
                }
            }
            else{
                self.showToast(msg:"没有数据")
            }
        default:
            break
        }
    }
    
   @objc override func shareTap() {
        //        //创建分享消息对象
        //        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        //        //创建图片内容对象
        //        UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
        //        //如果有缩略图，则设置缩略图
        //        shareObject.thumbImage = [UIImage imageNamed:@"icon"];
        //        [shareObject setShareImage:@"https://mobile.umeng.com/images/pic/home/social/img-1.png"];
        //        //分享消息对象设置分享内容对象
        //        messageObject.shareObject = shareObject;
    
        let content = self.removeHTML(htmlString: (model?.content)!)
        let message:UMSocialMessageObject = UMSocialMessageObject()
        let share: UMShareWebpageObject = UMShareWebpageObject.shareObject(withTitle:model?.title, descr: content, thumImage: consultationheaderView.headerImage.image)
        share.webpageUrl = appendUrl(suffix: (model?.shareUrl)!).absoluteString
        message.shareObject = share
        
        ONShareManager.setPreDefinePlatforms([NSNumber(integerLiteral: UMSocialPlatformType.wechatSession.rawValue)
            , NSNumber(integerLiteral: UMSocialPlatformType.QQ.rawValue), NSNumber(integerLiteral: UMSocialPlatformType.sina.rawValue), NSNumber(integerLiteral: UMSocialPlatformType.wechatTimeLine.rawValue)])
        ONShareManager.showShareMenuViewInWindowWithPlatformSelectionBlock { (platformType, info) in
            UMSocialManager.default().share(to: platformType, messageObject: message, currentViewController: self) { (shareResponse, error) in
                
                print("111");
                //                completion(shareResponse, error);
            }
        }
        //        ShareView().showShareView()
    }
    
    // 顶部刷新
    @objc func headerRefresh(){
        print("下拉刷新") // 结束刷新
        page = 0
        footerRefresh()
    }
    // 底部刷新
    @objc func footerRefresh(){
        print("上拉刷新")
        page += 1
        fetchCommentList(parameters: ["page":page,"pageSize":10,"commentType":"ARTICLE","jointId":(model?.id)!])
    }
    func reloadSuperTableView(view: ConsultationHeaderView) {
        mainTableView.reloadData()
    }
    func updateAttention(isAttention: Bool) {
        if isAttention{
            attentionCancelUser(parameters: ["concernUserId":(model?.author?.id)!])
        }
        else{
            attentionUser(parameters: ["concernUserId":(model?.author?.id)!])
        }
    }
    
    // MARK: - tableViewdelegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch consultationDetailType {
        case .news:
            return commentData.count
        case .video:
            return 0
        case .use:
            return 0
        }
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = commentData[indexPath.row]
        XHInputView.show(with: .large, configurationBlock: { inputView in
            inputView?.delegate = self
            inputView?.placeholder = "请输入回复评论文字..."
            inputView?.maxCount = 50
            inputView?.textViewBackgroundColor = UIColor.groupTableViewBackground
        }) { (str) -> Bool in
            if let text = str {
                if !text.isEmpty {
                    self.replyComment(parameter: ["replyContent":text,"replyCommentId":model.id!])
                    HUD.show(.label("加载中..."))
                    return true
                }
                return false
            }
            return false
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ConsultaionCommentTableViewCell
        cell.delegate = self
        cell.reportType = "article"
        cell.tag = indexPath.row
        cell.setData(datas: commentData[indexPath.row])
        return cell
    }
    
    ///MARK: - ConsultaionCommentTableViewCellDelegate
    func reloadSuperTable(_ cell: ConsultaionCommentTableViewCell) {
        let indexPath = mainTableView.indexPath(for: cell)
        mainTableView.reloadData()
    }
    
    func moreAct(model: myCommendModel) {
        let comm = CommentController()
        comm.model = model
        self.navigationController?.pushViewController(comm, animated: true)
        
    }

    func like(model: myCommendModel,tag:Int){
        
        commentLike(parameters: ["commentator":(MineInfoModel.share.userInfModel?.nickname!)!,"commentatorID":(MineInfoModel.share.userInfModel?.id!)!,
                                 "commentId":model.id!,"source":"article"],cellModel: model,tag:tag)
    }
    
    /// 设置底部视图
    private func setButtomView() -> UIView {
        let superSidMargin: CGFloat = 10
        let bottomHeight: CGFloat = 48
        let bottomView = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: bottomHeight))
        bottomView.backgroundColor = ONColor.cellBGColor
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: bottomView.width, height: bottomHeight))
        bgView.backgroundColor = ONColor.inputBoxBGColor
        bottomView.addSubview(bgView)
        addCornerWithView(aView: bgView, aCorners: [.bottomLeft, .bottomRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
//        setShadow(view: bgView, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
        let sideMargin: CGFloat = 8
        let tbMargin: CGFloat = 5
        
        let btn = UIButton(type: .custom)
        btn.setTitle("我也要说两句……", for: .normal)
        btn.backgroundColor = UIColor.white
        btn.contentHorizontalAlignment = .left
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0)
        btn.frame = CGRect(x: sideMargin, y: tbMargin, width: bgView.width - sideMargin * 2, height: bgView.height - tbMargin * 2)
        btn.setTitleColor(ONColor.placeholderTextColor, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btn.layer.cornerRadius = btn.height / 2
        btn.addTarget(self, action: #selector(inptBoxTap), for: .touchUpInside)
        bgView.addSubview(btn)
        return bottomView
    }
    
    /// MARK: - 设置弹出键盘
    @objc func inptBoxTap() {
        if !MineInfoModel.share.isLogin {
            let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
            self.navigationController?.pushViewController(loginVC, animated: true)
            return
        }
        XHInputView.show(with: .large, configurationBlock: { inputView in
            inputView?.delegate = self
            inputView?.placeholder = "请输入评论文字..."
            inputView?.maxCount = 50
            inputView?.textViewBackgroundColor = UIColor.groupTableViewBackground
        }) { (str) -> Bool in
            if let text = str {
                if !text.isEmpty {
                    self.sendComment(parameters: ["commentType":"ARTICLE","commentContent":text,"jointId":(self.model?.id)!])
                    HUD.show(.label("加载中..."))
                    return true
                }
                return false
            }
            return false
        }
    }
    
    func xhInputViewWillShow(_ inputView: XHInputView!) {
        IQKeyboardManager.shared.enable = false;
    }
    
    func xhInputViewWillHide(_ inputView: XHInputView!) {
        IQKeyboardManager.shared.enable = true;
    }
}

extension ConsultationDetailViewController {
    
    // 是否支持自转 看具体需求
    override var shouldAutorotate: Bool {
        return false
    }
    
    // 设置横屏方向
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        // 横屏 home键在右
        return .landscapeRight
    }
    
    
    @objc func rightButtonTap(_ btn: UIButton) {
        
        switch btn.tag {
        case 0:
            let imageSize = UIImage(named: "right_copy_page")
            guard let trueImageSize = imageSize else {return}
            if data.count > 0{
                RelevantRecommendationsView().showData(datas: data, rightMargin: trueImageSize.size.width * trueImageSize.scale - 50){(index) in
                    
                }
            }
            else{
                self.showToast(msg:"没有数据")
            }
        default:
            break
        }
    }
    /// 获取推荐内容
    func fetchRecommendList(objId:String,authorId:String,labelId:String) -> Void {
        let requesturl = "\(BaseURL)\(recommendContentUrl)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: ["objId":objId,"authorId":authorId,"labelId":labelId] ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let arr = json["data"].array!
                                        
                                        for subject in arr{
                                            
                                            let dic = subject.dictionary!
                                            let model = SearchRecommendModel(fromDic: dic)
                                            self.data.append(model)
                                        }
                                        self.consultationheaderView.updateItemsCollectionView(arr: self.data)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }

    /// 获取推荐内容
    func fetchRecommendShopList(labelId:String) -> Void {
        let requesturl = "\(BaseURL)\(recommendShoppingListUrl)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: ["labelId":labelId] ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let arr = json["data"]["rows"].array!
                                        
                                        for subject in arr{
                                            
                                            let dic = subject.dictionary!
                                            let model = GoodsModel(fromDic: dic)
                                            self.recommDatas.append(model)
                                        }
                                        if self.recommDatas.count == 0{
                                            self.recommBtn?.isHidden = true
                                        }
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    /// 获取评论内容
    func fetchCommentList(parameters: [String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(commentListUrl)"
        
        
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        
                                        if self.page == 1 {
                                            self.commentData.removeAll()
                                        }
                                        for subject in arr{
                                            
                                            let dic = subject.dictionary!
                                            var model = myCommendModel(fromDic: dic)
                                            
                                            let relatedComments = dic["relatedComments"]?.array!
                                            if let dict = dic["beRepliedUser"]?.dictionary {
                                                model.initReplied(dic: dict)
                                            }
                                            
                                            model.initRelatedComments(arr: relatedComments!)

                                            let author = dic["commentUser"]
                                            if !(author?.isEmpty)!{
                                                model.initAuthor(dic: (author?.dictionary!)!)
                                            }
                                            self.commentData.append(model)
                                        }
                                        if self.totalPage == self.commentData.count{
                                            self.mainTableView.mj_footer=nil
                                        }
                                        else{
                                            self.mainTableView.mj_footer = self.footer
                                        }
                                        self.mainTableView.reloadData()
                                        self.consultationheaderView.updateCommentTotalCount(count: self.totalPage)

                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    /// 发表评论
    func sendComment(parameters: [String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(sendCommentUrl)"
        
        
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        
                                        let commentCount:String = "\(Int((self.model?.comment)!)! + 1)"
                                        self.model?.comment = commentCount
                                        self.showToast(msg:"评论成功")
                                        DispatchQueue.main.async{
                                            self.headerRefresh()
                                        }
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                        
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"发送失败")
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    /// 关注用户
    func attentionUser(parameters: [String:Any]) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(attentionUserUrl)"
        
        
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg:"关注成功")
                                        self.consultationheaderView.updateAttentionState(attention: true)
                                    }
                                    else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                        
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"关注失败")
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    /// 取消关注用户
    func attentionCancelUser(parameters: [String:Any]) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(attentionCancelUserUrl)"
        
        
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg:"取消关注成功")
                                        self.consultationheaderView.updateAttentionState(attention: false)
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                        
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"请求失败")
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    /// 点赞
    func commentLike(parameters: [String:Any],cellModel:myCommendModel,tag:Int) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(commentLikeUrl)"
        
        
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    self.showToast(msg:json["message"].string!)
                                }
                            }else{
                                self.showToast(msg:String(describing: response.error))
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    /// 获取文章详情
    func fetchArticleDetail(id:String) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(fetchArticleDetailURl)/\(id)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: nil,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let dic = json["data"].dictionary!
                                        var amodel = ArticleModel(fromDic: dic)
                                        
                                        let labels = dic["labels"]?.array!
                                        
                                        amodel.initLabels(arr: labels!)
                                        
                                        let label = dic["label"]
                                        if !(label?.isEmpty)!{
                                            amodel.initLabel(dic: (label?.dictionary!)!)
                                        }
                                        let author = dic["author"]
                                        if !(author?.isEmpty)!{
                                            amodel.initAuthor(dic: (author?.dictionary!)!)
                                        }
                                        let grade = dic["author"]!["grade"]
                                        if !grade.isEmpty{
                                            amodel.author?.initGrade(dic: (grade.dictionary!))
                                        }
                                        let channel = dic["channel"]
                                        if !(channel?.isEmpty)!{
                                            amodel.initChannel(dic: (channel?.dictionary!)!)
                                        }
                                        self.model = amodel
                                    
                                        var headerView: UIView?
                                        switch self.consultationDetailType {
                                        case .news:
                                            self.consultationheaderView.delegateVc = self
                                            self.consultationheaderView.delegate = self
                                            self.consultationheaderView.setData(model: self.model!)
                                            headerView = self.consultationheaderView
                                        case .video:
                                            self.videoHeaderView.delegateVc = self
                                            self.videoHeaderView.setData(model: self.videoModel!)
                                            headerView = self.videoHeaderView
                                        case .use:
                                            self.useView.setData(model: self.videoModel!)
                                            headerView = self.useView
                                        }
                                        headerView?.autoresizingMask = .init(rawValue: 0)
                                        self.mainTableView.tableHeaderView = headerView

                                        if (self.model?.label) != nil{
                                            self.fetchRecommendList(objId: (self.model?.id)!,authorId: (self.model?.author?.id)!,labelId: (self.model?.label?.id)!)
                                            self.fetchRecommendShopList(labelId: (self.model?.label?.id)!)
                                        }
                                        else{
                                            self.fetchRecommendList(objId: (self.model?.id)!,authorId: (self.model?.author?.id)!,labelId: "")
                                            self.recommBtn?.isHidden = true
                                        }
                                        if amodel.collected! == "1"{
                                            self.collectionButton.isSelected = true
                                        }
                                        self.footerRefresh()
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                //                                self.showToast(msg:"请求失败"))
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    /// 收藏文章
    func collectionArticle(parameter:[String:Any],btn:UIButton) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(collectUrl)"
        
        Alamofire.request(requesturl, method: .post,
                          parameters: parameter,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        btn.isSelected = true
                                        self.model?.collected = "1"
                                        let favoriteCount:String = "\(Int((self.model?.favorite)!)! + 1)"
                                        self.model?.favorite = favoriteCount
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                //                                self.showToast(msg:"请求失败"))
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    /// 取消收藏文章
    func cancelCollectionArticle(parameter:[String:Any],btn:UIButton) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(cancelCollectUrl)"
        
        Alamofire.request(requesturl, method: .post,
                          parameters: parameter,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        btn.isSelected = false
                                        self.model?.collected = "0"
                                        let favoriteCount:String = "\(Int((self.model?.favorite)!)! - 1)"
                                        self.model?.favorite = favoriteCount
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                //                                self.showToast(msg:"请求失败"))
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    /// 回复评论
    func replyComment(parameter:[String:Any]) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(replyCommentUrl)"
        
        Alamofire.request(requesturl, method: .post,
                          parameters: parameter,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let commentCount:String = "\(Int((self.model?.comment)!)! + 1)"
                                        self.model?.comment = commentCount
                                        self.showToast(msg:"回复成功")
                                        self.headerRefresh()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                //                                self.showToast(msg:"请求失败"))
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    func fetchJbList() -> Void {
        let requesturl = "\(BaseURL)\(jbListUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: nil,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let data = json["data"].array
                                        var jbArr = Array<String>()
                                        for dic in data! {
                                            jbArr.append(dic["title"].string!)
                                        }
                                        self.jbList = jbArr
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    func jb(model:myCommendModel,reportType:String) -> Void {
        let report = ReportView()
        report.show(contnets: self.jbList, type: .report) { (index, view) in
            
            let content:String = report.titles[index]
            let parameter:[String : String] = ["source": reportType,"reportContent":content,"jointId":model.id!]
            Alamofire.request(appendUrl(suffix: reportUrl), method: .post,
                              parameters: parameter,
                              encoding: URLEncoding.default,
                              headers: ["token":MineInfoModel.share.token!]).responseJSON {
                                (response) in
                                
                                if(response.error == nil){
                                    if let result = response.result.value as? NSDictionary
                                    {
                                        
                                        let json = JSON(result)
                                        if json["code"].int == 1{
                                            self.showToast(msg:"举报成功")
                                            report.hide()
                                        }
                                        else{
                                            self.showToast(msg:"举报失败")
                                            report.hide()
                                        }
                                    }
                                }else{
                                    self.showToast(msg:"举报失败")
                                    report.hide()
                                }
                                
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if notiName != nil {
            NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: notiName!), object: self.model)
        }
    }
    
    
}

